/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */
import { hvigorCore } from '@ohos/hvigor';
import { ComponentPath } from '@ohos/sdkmanager-common';

import { CommonConst } from '../../const/common-const.js';
import { ProjectModelImpl } from '../../model/project/project-model-impl.js';
import { HmosSdkLoader } from '../../sdk/hmos-sdk-loader.js';
import { OhosSdkLoader } from '../../sdk/ohos-sdk-loader.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { TaskNames } from '../common/task-names.js';
import { deviceCoverageQueueCenter } from '../device-coverage-queue-center.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosModuleTask } from '../task/ohos-module-task.js';

/**
 * 调用ohos/coverage接口，生成测试覆盖率报告
 *
 * @2023/12/29
 */
export class GenerateUnitTestResult extends OhosModuleTask {
  private logger = OhosLogger.getLogger(GenerateUnitTestResult.name);
  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.Task.GENERATE_UNIT_TEST_RESULT);
  }

  private async getHmosPreviewerPath() {
    const sdkLoader = HmosSdkLoader.getInstance();
    const { compileSdkVersion } = this.targetData.getApiMeta();
    const componentsMap = await sdkLoader.getHmosSdkComponents(compileSdkVersion, [ComponentPath.PREVIEWER]);
    return componentsMap.get(ComponentPath.PREVIEWER)?.getLocation();
  }

  private async getOhosPreviewerPath() {
    const sdkLoader = OhosSdkLoader.getInstance();
    const { compileSdkVersion } = this.targetData.getApiMeta();
    const componentsMap = await sdkLoader.getOhosSdkComponents(compileSdkVersion, [ComponentPath.PREVIEWER]);
    const component = [...componentsMap.values()][0];
    return component?.getLocation();
  }

  private getPreviewerPath() {
    return this.targetData.isHarmonyOS() ? this.getHmosPreviewerPath() : this.getOhosPreviewerPath();
  }

  async doTaskAction() {
    await deviceCoverageQueueCenter.executeProxy(
      {
        logger: this.logger,
        sdkApiPath: (await this.getPreviewerPath()) || '',
        modulePath: this.pathInfo.getModulePath(),
        projectPath: (this.projectModel as ProjectModelImpl).getProjectDir(),
        coverage: hvigorCore.getExtraConfig().get(CommonConst.OHOS_TEST_COVERAGE) === 'true',
        hspDependencies: this.service.getHspDependencyPaths(),
      },
      'generateUnitTestResult',
    );
  }

  initTaskDepends() {
    // do nothing
  }
}
